<template>
  <div class="cart-page">
    <van-nav-bar title="我的购物车" left-arrow @click-left="goBack" />

    <!-- 加载状态 -->
    <van-loading v-if="loading" type="spinner" size="30" vertical />

    <!-- 购物车列表 -->
    <div class="cart-list" v-else-if="cartItems.length > 0">
      <div class="cart-item" v-for="item in cartItems" :key="item.id">
        <div class="item-img">
          <img :src="item.image_url" :alt="item.product_name" />
        </div>
        <div class="item-info">
          <h3 class="item-name">{{ item.product_name }}</h3>
          <div class="item-specs">{{ item.specs }}</div>
          <div class="item-toppings" v-if="item.toppings">{{ '小料：' + item.toppings }}</div>
          <div class="item-price">¥{{ item.price }}</div>
        </div>
        <div class="item-actions">
          <div class="quantity-control">
            <button @click="updateQuantity(item.id, item.quantity - 1)" :disabled="item.quantity <= 1">
              <van-icon name="minus" size="16" />
            </button>
            <span class="quantity">{{ item.quantity }}</span>
            <button @click="updateQuantity(item.id, item.quantity + 1)">
              <van-icon name="plus" size="16" />
            </button>
          </div>
          <button class="delete-btn" @click="confirmDelete(item.id)">
            <van-icon name="delete" color="#ff4d4f" size="20" />
          </button>
        </div>
      </div>
    </div>

    <!-- 空购物车 -->
    <div class="empty-cart" v-else>
      <van-empty description="购物车是空的" />
      <button class="go-shopping" @click="goBack">去逛逛</button>
    </div>

    <!-- 底部结算 -->
    <div class="cart-footer" v-if="cartItems.length > 0 && !loading">
      <div class="total-price">
        <span>合计：</span>
        <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <button class="checkout-btn" @click="checkout">结算</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant';
import api from '@/api/history';

const router = useRouter();
const cartItems = ref([]);
const loading = ref(false);
const errorMessage = ref('');

// 获取购物车列表
const getCartList = async () => {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await api.get('/cart/list');
    if (response.data && Array.isArray(response.data)) {
      cartItems.value = response.data;
    } else {
      throw new Error('返回数据格式不正确');
    }
  } catch (error) {
    console.error('获取购物车失败:', error);
    errorMessage.value = '加载购物车失败';
    showFailToast(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 更新商品数量
const updateQuantity = async (itemId, quantity) => {
  if (quantity < 1) return;
  try {
    const response = await api.patch(`/cart/item/${itemId}/quantity`, { quantity });
    if (response.status === 200) {
      const item = cartItems.value.find(i => i.id === itemId);
      if (item) item.quantity = quantity;
      showSuccessToast('数量已更新');
    } else {
      throw new Error(`更新失败: ${response.status}`);
    }
  } catch (error) {
    console.error('更新数量失败:', error);
    showFailToast('更新失败');
    // 失败后重新获取最新数据
    getCartList();
  }
};

// 确认删除对话框
const confirmDelete = (itemId) => {
  showConfirmDialog({
    title: '确认删除',
    message: '确定要从购物车删除此商品吗？',
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    confirmButtonColor: '#ff4d4f'
  })
    .then(() => {
      // 用户点击确认
      deleteItem(itemId);
    })
    .catch(() => {
      // 用户点击取消
    });
};

// 删除商品（优化版本）
const deleteItem = async (itemId) => {
  loading.value = true;
  errorMessage.value = '';

  try {
    // 1. 记录原始数据，用于回滚
    const originalItems = [...cartItems.value];
    const itemIndex = originalItems.findIndex(item => item.id === itemId);
    if (itemIndex === -1) {
      throw new Error('商品不存在');
    }

    // 2. 先从UI中移除商品（乐观更新）
    cartItems.value.splice(itemIndex, 1);

    // 3. 发送删除请求到后端
    const response = await api.delete(`/cart/item/${itemId}`);

    // 4. 验证响应结果
    if (response.status === 200) {
      showSuccessToast('已删除');
    } else {
      // 恢复原始数据
      cartItems.value = originalItems;
      throw new Error(`删除失败: ${response.status}`);
    }
  } catch (error) {
    console.error('删除失败:', error);
    console.error('请求URL:', error.config?.url);
    console.error('响应数据:', error.response?.data);

    errorMessage.value = '删除失败，请重试';
    showFailToast(errorMessage.value);

    // 确保数据一致性，重新加载购物车
    await getCartList();
  } finally {
    loading.value = false;
  }
};

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + Number(item.price) * item.quantity, 0);
});

// 返回上一页
const goBack = () => router.back();

// 结算：传递商品product_id到订单页
const checkout = () => {
  if (cartItems.value.length === 0) {
    showFailToast('购物车为空');
    return;
  }
  // 收集所有商品的product_id
  const productIds = cartItems.value.map(item => item.product_id);
  console.log('传递的productIds:', productIds); // 确认ID是否正确
  router.push({
    path: '/order',
    query: {
      productIds: productIds.join(',')
    }
  });
};

// 初始化加载
onMounted(() => {
  getCartList();
});
</script>

<style scoped>
.cart-page {
  max-width: 600px;
  margin: 0 auto;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

/* 购物车列表 */
.cart-list {
  padding: 10px;
}

.cart-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 10px;
}

.item-img {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
  margin-right: 10px;
}

.item-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex-grow: 1;
  min-width: 0;
}

.item-name {
  font-size: 16px;
  color: #333;
  margin: 0 0 5px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-specs,
.item-toppings {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.item-price {
  font-size: 14px;
  color: #e63946;
  font-weight: bold;
}

/* 数量操作与删除 */
.item-actions {
  display: flex;
  align-items: center;
  flex-direction: column;
  gap: 15px;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 5px;
}

.quantity-control button {
  width: 25px;
  height: 25px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-control button:disabled {
  background-color: #f5f5f5;
  color: #ccc;
}

.quantity {
  width: 30px;
  text-align: center;
  font-size: 14px;
}

.delete-btn {
  border: none;
  background: none;
  padding: 5px;
}

/* 空购物车 */
.empty-cart {
  text-align: center;
  padding-top: 50px;
}

.go-shopping {
  margin-top: 20px;
  padding: 8px 20px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 底部结算栏 */
.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background-color: #fff;
  padding: 0 15px;
  border-top: 1px solid #eee;
  max-width: 600px;
  margin: 0 auto;
}

.total-price {
  font-size: 14px;
}

.total-price .price {
  font-size: 18px;
  color: #e63946;
  font-weight: bold;
}

.checkout-btn {
  padding: 8px 25px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>